import React, { Component, Fragment } from "react";
import {
  Button,
  Table,
  Select,
  Divider,
  Popconfirm,
  Badge,
  Form,
  Row,
  Col,
  Input,
  message,
  Alert
} from "antd";
import { connect } from "dva";
// import moment from "moment";
import { Link } from "dva/router";
import styles from "./MessageSource.less";
import { getChannelText } from "../../channelType";
import api from "../../../services/publicApi";
import ToggleColumns from "../../../components/toggleColumns";
import { getCurrentTenant } from "../../../utils/utils";

// const { Search } = Input;
// const { RangePicker } = DatePicker;

@connect(stores => ({
  messageData: stores.messageList,
  channelDictionaryModel: stores.channelDictionaryModel,
  userData: stores.user
}))
@Form.create()
class MessageSource extends Component {
  state = {
    pageNum: 1,
    pageSize: 10,
    showColumns: [],
    columnCfg: {},
    userId: "",
    selectedRowKeys: []
  };

  componentDidMount() {
    this.filterFun();
    const { userId } = this.state;
    if (userId) {
      // 获取隐藏表格配置
      this.getColumnCfg(userId);
    }
  }

  componentDidUpdate(_, prevState) {
    const { userId } = this.state;
    if (userId && userId !== prevState.userId) {
      // 获取隐藏表格配置
      this.getColumnCfg(userId);
    }
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const { userInfo = {} } = nextProps.userData;
    if (userInfo.userId && userInfo.userId !== prevState.userId) {
      return { userId: userInfo.userId };
    }
    return null;
  }

  getColumnCfg = userId => {
    api.getColumnsByTable({ user: userId, tag: "msgSendTask" }).then(res => {
      if (res.success) {
        if (res.datas.length === 0 || res.datas[0].config === "") {
          this.setState({
            columnCfg: res.datas[0] || {},
            showColumns: this.getColumns()
          });
        } else {
          const hiddenArr = res.datas[0].config.split(",");
          this.setState({
            columnCfg: res.datas[0] || {},
            showColumns: this.getColumns().filter(
              c => !hiddenArr.find(hc => hc === c.dataIndex)
            )
          });
        }
      } else {
        message.error(res.errMsg);
      }
    });
  };

  onSetColumns = (shows, hiddens) => {
    const { userId, columnCfg } = this.state;
    this.setState({
      showColumns: shows
    });
    // 同步动态表格隐藏列信息
    api
      .updateColumnsByTable({
        config: hiddens.map(h => h.dataIndex).join(","),
        user: userId,
        tag: columnCfg.tag || "msgSendTask",
        id: columnCfg.id
      })
      .then(res => {
        if (!res.success) {
          message.warning("动态表格同步失败");
        }
      });
  };

  resetSelectedRowKeys = () => {
    this.setState(state => ({ ...state, selectedRowKeys: [] }));
  };

  renderState = (status, text) => {
    if (status === 1) {
      return <Badge status="success" text={text} />;
    }
    if (status === -1) {
      return <Badge status="error" text={text} />;
    }
    if (status === 2) {
      return <Badge status="default" text={text} />;
    }
    return <Badge status="warning" text={text} />;
  };

  renderType = text => {
    const { channelDictionaryModel } = this.props;
    const { channelsTypesData = [] } = channelDictionaryModel;
    return <span>{getChannelText(channelsTypesData, text)}</span>;
  };

  dateChange = e => {
    if (e && e.length > 0) {
      this.setState(
        {
          creTimeStart: e[0].format("YYYY-MM-DD"),
          creTimeEnd: e[1].format("YYYY-MM-DD 23:59:59"),
          pageNum: 1
        },
        () => {
          this.filterFun();
        }
      );
    } else {
      this.setState(
        {
          creTimeStart: "",
          creTimeEnd: "",
          pageNum: 1
        },
        () => {
          this.filterFun();
        }
      );
    }
  };

  handleTableChange = e => {
    const { current, pageSize } = e;
    // const { ownerDept, auditStatus, pushChannelType } = this.state;
    // let newOwnerDept = filters.ownerDeptName ? filters.ownerDeptName : [];
    // // "状态"筛选变更，更新"归属部门"选中值状态
    // if (filters.auditStatus && filters.auditStatus[0] !== auditStatus[0]) {
    //   newOwnerDept = [];
    // }
    this.setState(
      {
        pageSize,
        pageNum: current
        // :
        //   (filters.ownerDeptName &&
        //     filters.ownerDeptName[0] !== ownerDept[0]) ||
        //   (filters.auditStatus && filters.auditStatus[0] !== auditStatus[0]) ||
        //   (filters.pushChannelType &&
        //     filters.pushChannelType !== pushChannelType)
        //     ? 1
        //     : current,
        // pageSize,
        // ascOrDesc: sorter.order && sorter.order === "ascend" ? "asc" : "desc",
        // ownerDept: newOwnerDept,
        // auditStatus: filters.auditStatus ? filters.auditStatus : [],
        // pushChannelId: filters.pushChannelName ? filters.pushChannelName : [],
        // pushChannelType: filters.pushChannelType ? filters.pushChannelType : []
      },
      () => {
        this.filterFun();
      }
    );
  };

  handleSearch = e => {
    this.setState(
      {
        sourceName: e,
        pageNum: 1
      },
      () => {
        this.filterFun();
      }
    );
  };

  clearChange = e => {
    if (e.target.value !== "") return;
    this.setState(
      {
        sourceName: "",
        pageNum: 1
      },
      () => {
        this.filterFun();
      }
    );
  };

  filterFun = () => {
    const { pageSize, pageNum } = this.state;
    const { dispatch, form } = this.props;
    const { getFieldsValue } = form;
    dispatch({
      type: "messageList/messageList",
      payload: {
        pageNum: String(pageNum),
        pageSize: String(pageSize),
        ...getFieldsValue()
      }
    });
    // dispatch({
    //   type: "messageList/messageDept",
    //   payload: { ownerDept: "" }
    // });
    // dispatch({ type: "addPlan/getPushChannel", payload: { ...temp } });
  };

  handleCommit = record => {
    const { dispatch } = this.props;
    dispatch({
      type: "messageList/updateStatus",
      payload: {
        isEnabled: record.isEnabled === "Y" ? "N" : "Y",
        msgSourceId: record.msgSourceId
      }
    }).then(res => {
      if (res.errCode === 0) {
        message.success("操作成功");
        this.filterFun();
      } else {
        message.error(`操作失败，${res.errMsg}`);
      }
    });
  };

  deleteconfirm = record => {
    const { dispatch } = this.props;
    dispatch({
      type: "messageList/delMessage",
      payload: { msgSourceId: record.msgSourceId, sourceId: record.sourceId }
    }).then((res = {}) => {
      if (res.errCode === 0) {
        message.success("删除成功");
        this.filterFun();
      } else {
        message.error(`删除失败, ${res.msg}`);
      }
    });
  };

  onReset() {
    const { form } = this.props;
    form.resetFields();
  }

  onSelectChange = selectedKeys => {
    const { selectedRowKeys = [] } = this.state;
    const { messageData } = this.props;
    const { messageList = [] } = messageData;
    // 获取当前页所有的 key
    const allKeysInCurrentPage = messageList.map(item => item.msgSourceId);
    // 获取非当前页选中的 key
    const selectedKeysNotInCurrentPage = selectedRowKeys.filter(
      key => !allKeysInCurrentPage.includes(key)
    );
    // 获取当前页选中的的 key
    const selectedKeysInCurrentPage = selectedKeys.filter(key =>
      allKeysInCurrentPage.includes(key)
    );
    // 合并生成新的 selectedRowKeys
    this.setState(state => ({
      ...state,
      selectedRowKeys: [
        ...selectedKeysNotInCurrentPage,
        ...selectedKeysInCurrentPage
      ]
    }));
  };

  handleSubmit() {
    this.filterFun();
  }

  getColumns = () => {
    const {
      channelDictionaryModel: { channelsTypesData = [] }
    } = this.props;
    const { pageNum, pageSize } = this.state;
    return [
      {
        title: "序号",
        width: 50,
        dataIndex: "index",
        render: (a, b, c) => <span>{pageSize * (pageNum - 1) + c + 1}</span>
      },
      {
        title: "租户编码",
        ellipsis: true,
        dataIndex: "tenantCode"
      },
      {
        title: "租户名称",
        ellipsis: true,
        dataIndex: "tenantName"
      },
      {
        title: "发送任务编码",
        ellipsis: true,
        dataIndex: "sourceCode"
      },
      {
        title: "发送任务名称",
        ellipsis: true,
        dataIndex: "sourceName"
      },
      {
        title: "消息源编码",
        ellipsis: true,
        dataIndex: "messageCode"
      },
      {
        title: "消息源名称",
        ellipsis: true,
        dataIndex: "messageName"
      },
      {
        title: "场景编码",
        ellipsis: true,
        dataIndex: "sceneCode"
      },
      {
        title: "场景名称",
        ellipsis: true,
        dataIndex: "sceneName"
      },
      {
        title: "消息模版编码",
        ellipsis: true,
        dataIndex: "templateCode"
      },
      {
        title: "消息模版名称",
        ellipsis: true,
        dataIndex: "templateName"
      },
      {
        title: "接收组编码",
        ellipsis: true,
        dataIndex: "receiveGroupCode"
      },
      {
        title: "接收渠道类型",
        ellipsis: true,
        dataIndex: "pushChannelList1",
        render: (_, record) =>
          record.pushChannelList
            .map(l => getChannelText(channelsTypesData, l.channelType))
            .join(",")
      },
      {
        title: "接收渠道编码",
        ellipsis: true,
        dataIndex: "pushChannelList2",
        render: (_, record) =>
          record.pushChannelList.map(l => (
            <div
              style={{
                overflow: "hidden",
                whiteSpace: "nowrap",
                textOverflow: "ellipsis"
              }}
              title={`${getChannelText(channelsTypesData, l.channelType)}：${l.channelCode}`}
              key={l.channelCode}
            >
              {getChannelText(channelsTypesData, l.channelType)}：
              {l.channelCode}
            </div>
          ))
      },
      {
        title: "接收渠道名称",
        ellipsis: true,
        dataIndex: "pushChannelList3",
        render: (_, record) =>
          record.pushChannelList.map(l => (
            <div
              style={{
                overflow: "hidden",
                whiteSpace: "nowrap",
                textOverflow: "ellipsis"
              }}
              title={`${getChannelText(channelsTypesData, l.channelType)}：${l.description}`}
              key={l.channelCode}
            >
              {getChannelText(channelsTypesData, l.channelType)}：
              {l.description}
            </div>
          ))
      },
      {
        title: "状态",
        dataIndex: "isEnabled",
        render: text => <span>{text === "Y" ? "启用" : "停用"}</span>
      },
      {
        title: "操作",
        width: 180,
        fixed: "right",
        dataIndex: "operate",
        render: (text, record) => {
          const states = { operate: "mod", msgSourceId: record.msgSourceId };
          const isDisable = record.isEnabled === "Y";
          const offLineTitle =
            record.isEnabled === "Y" ? "确定停用吗" : "确定启用吗";
          return (
            <span>
              <Link
                to={`/messageCenter/messageManager/messageSource/messageAdd?key=${JSON.stringify(
                  states
                )}`}
                disabled={isDisable}
              >
                编辑
              </Link>
              <Divider type="vertical" />
              <Popconfirm
                title="你是否要删除此发送任务?"
                onConfirm={() => this.deleteconfirm(record)}
                onCancel={this.endcancel}
                okText="确定"
                cancelText="取消"
                placement="topRight"
              >
                <a disabled={isDisable}>删除</a>
              </Popconfirm>
              <Divider type="vertical" />
              <Popconfirm
                title={offLineTitle}
                onConfirm={() => this.handleCommit(record)}
              >
                {record.isEnabled === "Y" ? (
                  <a>停用</a>
                ) : (
                  <a disabled={isDisable}>启用</a>
                )}
              </Popconfirm>
              {/* <Divider type="vertical" />
              <a>测试发送</a> */}
            </span>
          );
        }
      }
    ];
  };

  render() {
    // getColumnSearchProps = () => {}, , ownerDept
    const {
      messageData,
      form
      // channelDictionaryModel: { channelsTypesData = [] }
    } = this.props;
    const { pageNum, showColumns, selectedRowKeys } = this.state;
    const {
      loading,
      messageList = [],
      listTotal = 0
      // deptList = []
    } = messageData;
    // const { channelDictionaryModel } = this.props;
    // const { CHANNEL_VALUE = [] } = channelDictionaryModel;
    const { getFieldDecorator } = form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    };
    const keys = { operate: "add" };
    const rowSelection = {
      onChange: this.onSelectChange,
      columnWidth: 65,
      selectedRowKeys
    };
    return (
      <div className={styles.root}>
        <div className={styles.titleBox}>发送任务配置</div>
        <div style={{ padding: "24px" }}>
          <div
            style={{
              fontSize: 14,
              color: "rgba(0,0,0,0.85)",
              marginBottom: 16,
              display: "flex",
              alignItems: "center",
              padding: "14px 16px",
              background: "#fff"
            }}
          >
            <Form
              {...formItemLayout}
              onSubmit={() => this.handleSubmit()}
              style={{ width: "100%" }}
            >
              <Row>
                <Col span={6}>
                  <Form.Item
                    label="消息发送任务"
                    labelCol={{ span: 10 }}
                    wrapperCol={{ span: 14 }}
                  >
                    {getFieldDecorator("sourceNameOrSourceCode")(
                      <Input placeholder="请输入消息发送任务ID或名称" />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="消息接收组">
                    {getFieldDecorator("receiveGroupCodeOrGroupName")(
                      <Input placeholder="请输入接收组编码或名称" />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="场景">
                    {getFieldDecorator("sceneCodeOrSceneName")(
                      <Input placeholder="请输入场景编码或名称" />
                    )}
                  </Form.Item>
                </Col>
                {/* <Col span={6}>
                  <Form.Item label="接受渠道类型">
                    {getFieldDecorator("pushChannelType")(
                      <Select placeholder="请选择" allowClear>
                        {channelsTypesData.map(d => (
                          <Select.Option key={d.value} value={d.value}>
                            {d.des}
                          </Select.Option>
                        ))}
                      </Select>
                    )}
                  </Form.Item>
                </Col> */}
                <Col span={6}>
                  <Form.Item
                    label="接收渠道账户"
                    labelCol={{ span: 10 }}
                    wrapperCol={{ span: 14 }}
                  >
                    {getFieldDecorator("pushChannelCodeOrPushChannelName")(
                      <Input placeholder="请输入渠道名称或者编码" />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item
                    label="消息源"
                    labelCol={{ span: 10 }}
                    wrapperCol={{ span: 14 }}
                  >
                    {getFieldDecorator("messageNameOrMessageCode")(
                      <Input placeholder="请输入消息源编码或名称" />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="状态">
                    {getFieldDecorator("isEnabled")(
                      <Select placeholder="请选择" allowClear>
                        <Select.Option value="Y">启用</Select.Option>
                        <Select.Option value="N">停用</Select.Option>
                      </Select>
                    )}
                  </Form.Item>
                </Col>
                <Col span={6} style={{ textAlign: "right" }}>
                  <Button
                    type="primary"
                    style={{ marginRight: "10px" }}
                    // htmlType="submit"
                    onClick={() => this.handleSubmit()}
                  >
                    搜索
                  </Button>
                  <Button onClick={() => this.onReset()}>重置</Button>
                </Col>
              </Row>
            </Form>
          </div>
          <div className={styles.bottomCard}>
            <div className={styles.titleRow}>
              <div>
                <Button
                  type="primary"
                  style={{ marginLeft: 10 }}
                  onClick={() => {
                    window.open(
                      `/mgt/excel/outputMsgSourceExcel?param=${selectedRowKeys.join(
                        ","
                      )}`,
                      "_blank"
                    );
                  }}
                  disabled={selectedRowKeys.length === 0}
                >
                  批量导出
                </Button>
                {selectedRowKeys.length !== 0 && (
                  <Fragment>
                    <Alert
                      style={{
                        display: "inline-block",
                        padding: "5px 8px",
                        marginLeft: 10
                      }}
                      message={`已选中 ${selectedRowKeys.length} 条记录`}
                      type="info"
                    />
                    &nbsp;&nbsp;
                  </Fragment>
                )}
              </div>
              <div>
                <ToggleColumns
                  originColumns={this.getColumns()}
                  showColumns={showColumns}
                  onSetColumns={this.onSetColumns}
                />
                <Link
                  to={`/messageCenter/messageManager/messageSource/messageAdd?key=${JSON.stringify(
                    keys
                  )}`}
                >
                  <Button
                    style={{ marginLeft: 10 }}
                    type="primary"
                    disabled={getCurrentTenant().id === "100000"}
                  >
                    新增
                  </Button>
                </Link>
              </div>
            </div>
            <Table
              style={{ background: "#fff" }}
              columns={showColumns}
              size="middle"
              dataSource={messageList}
              rowSelection={rowSelection}
              loading={loading}
              locale={{ emptyText: "暂无数据！" }}
              scroll={messageList.length === 0 ? { x: false } : { x: 2003 }}
              rowKey="msgSourceId"
              onChange={(e, filters, sorter) =>
                this.handleTableChange(e, filters, sorter)
              }
              pagination={{
                defaultPageSize: 10,
                showQuickJumper: true,
                showSizeChanger: true,
                current: pageNum,
                total: listTotal,
                showTotal: total => `共有 ${total} 条`
              }}
            />
          </div>
        </div>
      </div>
    );
  }
}

export default MessageSource;
